package cn.nfwx.tv.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import cn.nfwx.tv.BuildConfig;
import cn.nfwx.tv.R;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.util.LogUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 后台下载服务
 * Created by zhouzechao on 2018/1/3.
 */
public class DownloadService extends Service {
    public static final String TAG = "DownloadService";
    public static final String ACTION = "cn.southtv.download_video";
    public static final String STATUS = "status";
    public static final String PROGRESS = "progress";
    public static final boolean DEBUG = BuildConfig.IS_RELEASE;

    //下载大小通知频率
    public static final int UPDATE_NUMBER_SIZE = 1;
    public static final int DEFAULT_RES_ID = -1;

    public static final int UPDATE_PROGRESS_STATUS = 0;
    public static final int UPDATE_ERROR_STATUS = -1;
    public static final int UPDATE_SUCCESS_STATUS = 1;

    private DownloadProgressListener downloadProgressListener;
    private DownloadBinder downloadBinder = new DownloadBinder();

    private String downloadUrl;
    private int icoResId;
    private int icoSmallResId;
    private String storeDir;
    private String fileName;
    private int updateProgress;
    private int downloadNotificationFlag;
    private int downloadErrorNotificationFlag;
    private int downloadSuccessNotificationFlag;
    private boolean isSendBroadcast;

    private boolean startDownload;//开始下载
    private int lastProgressNumber;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private int notifyId = 100;
    private String notifyTitle;
    private LocalBroadcastManager localBroadcastManager;
    private Intent localIntent;

    //params
    private static final String URL = "downloadUrl";
    private static final String ICO_RES_ID = "icoResId";
    private static final String ICO_SMALL_RES_ID = "icoSmallResId";
    private static final String UPDATE_PROGRESS = "updateProgress";
    private static final String STORE_DIR = "storeDir";
    private static final String FILE_NAME = "filename";
    private static final String DOWNLOAD_NOTIFICATION_TITLE = "downloadnotificationtitle";
    private static final String DOWNLOAD_NOTIFICATION_FLAG = "downloadNotificationFlag";
    private static final String DOWNLOAD_SUCCESS_NOTIFICATION_FLAG = "downloadSuccessNotificationFlag";
    private static final String DOWNLOAD_ERROR_NOTIFICATION_FLAG = "downloadErrorNotificationFlag";
    private static final String IS_SEND_BROADCAST = "isSendBroadcast";


    public void setDownloadProgressListener(DownloadProgressListener downloadProgressListener) {
        this.downloadProgressListener = downloadProgressListener;
    }

    /**
     * 关闭服务
     *
     * @param context
     */
    public static void stop(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(context, DownloadService.class);
        context.stopService(intent);
    }

    public class DownloadBinder extends Binder {
        public void setUpdateProgressListener(DownloadProgressListener listener) {
            DownloadService.this.setDownloadProgressListener(listener);
        }
    }

    /**
     * 下载监听
     */
    public interface DownloadProgressListener {
        void start(String requestTag);

        void update(String requestTag, int progress);

        void success(String requestTag, String path);

        void error(String requestTag);
    }

    private static String getSaveFileName(DownloadService service) {
        if (!TextUtils.isEmpty(service.fileName)) {
            return service.fileName;
        }
        if (service.downloadUrl == null || TextUtils.isEmpty(service.downloadUrl)) {
            return "noName.apk";
        }
        return service.downloadUrl.substring(service.downloadUrl.lastIndexOf("/"));
    }

    private static String getDownloadDir(DownloadService service) {
        return service.storeDir;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return downloadBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (downloadProgressListener != null) {
            downloadProgressListener = null;
        }
        manager.cancel(notifyId);
        localIntent = null;
        builder = null;
        localBroadcastManager = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!startDownload && intent != null) {
            startDownload = true;
            downloadUrl = intent.getStringExtra(URL);
            icoResId = intent.getIntExtra(ICO_RES_ID, DEFAULT_RES_ID);
            icoSmallResId = intent.getIntExtra(ICO_SMALL_RES_ID, DEFAULT_RES_ID);
            storeDir = intent.getStringExtra(STORE_DIR);
            updateProgress = intent.getIntExtra(UPDATE_PROGRESS, UPDATE_NUMBER_SIZE);
            downloadNotificationFlag = intent.getIntExtra(DOWNLOAD_NOTIFICATION_FLAG, 0);
            downloadErrorNotificationFlag = intent.getIntExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, 0);
            downloadSuccessNotificationFlag = intent.getIntExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, 0);
            isSendBroadcast = intent.getBooleanExtra(IS_SEND_BROADCAST, false);
            fileName = intent.getStringExtra(FILE_NAME);

            notifyTitle = intent.getStringExtra(DOWNLOAD_NOTIFICATION_TITLE);
            if (TextUtils.isEmpty(notifyTitle)) {
                notifyTitle = getApplicationName();
            }

            if (DEBUG) {
                Log.d(TAG, "downloadUrl: " + downloadUrl);
                Log.d(TAG, "icoResId: " + icoResId);
                Log.d(TAG, "icoSmallResId: " + icoSmallResId);
                Log.d(TAG, "storeDir: " + storeDir);
                Log.d(TAG, "updateProgress: " + updateProgress);
                Log.d(TAG, "downloadNotificationFlag: " + downloadNotificationFlag);
                Log.d(TAG, "downloadErrorNotificationFlag: " + downloadErrorNotificationFlag);
                Log.d(TAG, "downloadSuccessNotificationFlag: " + downloadSuccessNotificationFlag);
                Log.d(TAG, "isSendBroadcast: " + isSendBroadcast);
            }

            buildNotification();
            buildBroadcast();

            /*downloadApkTask = new DownloadApk(this);
            downloadApkTask.execute(downloadUrl);*/

            if (TextUtils.isEmpty(downloadUrl)) {
                return super.onStartCommand(intent, flags, startId);
            }
            String request_tag = "requestTimelineVideoPath_" + downloadUrl;
            CustomOkHttpClient.doGet(downloadUrl, request_tag, new DownloadCallBack(this, request_tag));
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        if (applicationInfo != null) {
            String applicationName =
                    (String) packageManager.getApplicationLabel(applicationInfo);
            return applicationName;
        }
        return "南方无线电视";
    }

    private void buildBroadcast() {
        if (!isSendBroadcast) {
            return;
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localIntent = new Intent(ACTION);
    }

    private void sendLocalBroadcast(int status, int progress) {
        if (!isSendBroadcast || localIntent == null) {
            return;
        }
        localIntent.putExtra(STATUS, status);
        localIntent.putExtra(PROGRESS, progress);
        localBroadcastManager.sendBroadcast(localIntent);
    }

    private void buildNotification() {
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(this, "default");
        builder.setContentTitle(notifyTitle)
                .setWhen(System.currentTimeMillis())
                .setProgress(100, 1, false)
                .setSmallIcon(icoSmallResId)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(), icoResId))
                .setDefaults(downloadNotificationFlag);

        manager.notify(notifyId, builder.build());
    }

    private void start(String requestTag) {
        builder.setContentTitle(notifyTitle);
        builder.setContentText(getString(R.string.download_prepare));
        manager.notify(notifyId, builder.build());
        sendLocalBroadcast(UPDATE_PROGRESS_STATUS, 1);
        if (downloadProgressListener != null) {
            downloadProgressListener.start(requestTag);
        }
    }

    private void update(String requestTag, int progress) {
        if (progress - lastProgressNumber > updateProgress) {
            lastProgressNumber = progress;
            builder.setProgress(100, progress, false);
            builder.setContentText(getString(R.string.download_progress, progress, "%"));
            manager.notify(notifyId, builder.build());
            sendLocalBroadcast(UPDATE_PROGRESS_STATUS, progress);
            if (downloadProgressListener != null) {
                downloadProgressListener.update(requestTag, progress);
            }
        }
    }

    private void success(String requestTag, String path) {
        builder.setProgress(0, 0, false);
        builder.setContentText(getString(R.string.download_success));
        Intent i = playIntent();
        PendingIntent intent = PendingIntent.getActivities(this, 0, new Intent[]{i}, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(intent);
        builder.setDefaults(downloadSuccessNotificationFlag);
        Notification n = builder.build();
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_SUCCESS_STATUS, 100);
        if (downloadProgressListener != null) {
            downloadProgressListener.success(requestTag, path);
        }
        startDownload = false;
        stopSelf();
    }

    private static Intent playIntent() {
        try {
            Intent albumIntent = new Intent(Intent.ACTION_PICK);
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "video/*");
            return albumIntent;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void error(String requestTag) {
        if (builder == null) {
            return;
        }
        builder.setContentText(NFWXApplication.getInstance().
                getString(R.string.download_error));
        builder.setProgress(0, 0, false);
        builder.setDefaults(downloadErrorNotificationFlag);
        Notification n = builder.build();
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_ERROR_STATUS, -1);
        if (downloadProgressListener != null) {
            downloadProgressListener.error(requestTag);
        }
        startDownload = false;
        stopSelf();
    }

    private static class DownloadCallBack implements okhttp3.Callback {

        private WeakReference<DownloadService> updateServiceWeakReference;
        private String requestTag;

        public DownloadCallBack(DownloadService service) {
            updateServiceWeakReference = new WeakReference<>(service);
        }

        public DownloadCallBack(DownloadService service, String request_tag) {
            updateServiceWeakReference = new WeakReference<>(service);
            requestTag = request_tag;
        }

        @Override
        public void onFailure(Call call, IOException e) {
            DownloadService service = updateServiceWeakReference.get();
            if (service != null) {
                service.error(requestTag);
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            DownloadService service = updateServiceWeakReference.get();
            InputStream inputStream = response.body().byteStream();
            FileOutputStream fileOutputStream = null;
            long updateTotalSize = 0;
            try {
                // start
                service.start(requestTag);

                File file = new File(DownloadService.getDownloadDir(service),
                        DownloadService.getSaveFileName(service));

                File dir = file.getParentFile();
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                updateTotalSize = response.body().contentLength();

                if (file.exists()) {
                    if (updateTotalSize == file.length()) {
                        // 下载完成
                        service.success(requestTag, file.getAbsolutePath());
                        return;
                    } else {
                        file.delete();
                    }
                }
                file.createNewFile();

                fileOutputStream = new FileOutputStream(file, false);

                byte[] buffer = new byte[1024];
                int len = 0;
                long sum = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                    sum += len;
                    int progress = (int) (sum * 100 / updateTotalSize);
                    service.update(requestTag, progress);
                }
                service.success(requestTag, file.getAbsolutePath());
                fileOutputStream.flush();
                response.body().close();
            } catch (Exception e) {
                service.error(requestTag);
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static class Builder {

        private String downloadUrl;
        private int icoResId = DEFAULT_RES_ID;             //default app ico
        private int icoSmallResId = DEFAULT_RES_ID;
        private int updateProgress = UPDATE_NUMBER_SIZE;   //update notification progress when it add number
        private String storeDir;          //default sdcard/Android/package/update
        private int downloadNotificationFlag;
        private int downloadSuccessNotificationFlag;
        private int downloadErrorNotificationFlag;
        private boolean isSendBroadcast;
        private String fileName;
        private ServiceConnection connection;
        private String title;

        protected Builder(String downloadUrl) {
            this.downloadUrl = downloadUrl;
        }

        public static Builder create(String downloadUrl) {
            if (downloadUrl == null) {
                throw new NullPointerException("downloadUrl == null");
            }
            return new Builder(downloadUrl);
        }

        public String getDownloadUrl() {
            return downloadUrl;
        }

        public int getIcoResId() {
            return icoResId;
        }

        public Builder setIcoResId(int icoResId) {
            this.icoResId = icoResId;
            return this;
        }

        public int getIcoSmallResId() {
            return icoSmallResId;
        }

        public Builder setIcoSmallResId(int icoSmallResId) {
            this.icoSmallResId = icoSmallResId;
            return this;
        }

        public int getUpdateProgress() {
            return updateProgress;
        }

        public Builder setUpdateProgress(int updateProgress) {
            if (updateProgress < 1) {
                throw new IllegalArgumentException("updateProgress < 1");
            }
            this.updateProgress = updateProgress;
            return this;
        }

        public String getStoreDir() {
            return storeDir;
        }

        public Builder setStoreDir(String storeDir) {
            this.storeDir = storeDir;
            return this;
        }

        public int getDownloadNotificationFlag() {
            return downloadNotificationFlag;
        }

        public Builder setDownloadNotificationFlag(int downloadNotificationFlag) {
            this.downloadNotificationFlag = downloadNotificationFlag;
            return this;
        }

        public int getDownloadSuccessNotificationFlag() {
            return downloadSuccessNotificationFlag;
        }

        public Builder setDownloadSuccessNotificationFlag(int downloadSuccessNotificationFlag) {
            this.downloadSuccessNotificationFlag = downloadSuccessNotificationFlag;
            return this;
        }

        public int getDownloadErrorNotificationFlag() {
            return downloadErrorNotificationFlag;
        }

        public Builder setDownloadErrorNotificationFlag(int downloadErrorNotificationFlag) {
            this.downloadErrorNotificationFlag = downloadErrorNotificationFlag;
            return this;
        }

        public boolean isSendBroadcast() {
            return isSendBroadcast;
        }

        public Builder setIsSendBroadcast(boolean isSendBroadcast) {
            this.isSendBroadcast = isSendBroadcast;
            return this;
        }

        public String getFileName() {
            return fileName;
        }

        public Builder setFileName(String fileName) {
            this.fileName = fileName;
            return this;
        }

        public Builder build(Context context) {
            if (context == null) {
                throw new NullPointerException("context == null");
            }
            Intent intent = new Intent();

            intent.setClass(context, DownloadService.class);
            intent.putExtra(URL, downloadUrl);

            if (connection != null) {
                context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }

            if (icoResId == DEFAULT_RES_ID) {
                icoResId = getIcon(context);
            }

            if (icoSmallResId == DEFAULT_RES_ID) {
                icoSmallResId = icoResId;
            }
            intent.putExtra(ICO_RES_ID, icoResId);
            intent.putExtra(STORE_DIR, storeDir);
            intent.putExtra(FILE_NAME, fileName);
            intent.putExtra(ICO_SMALL_RES_ID, icoSmallResId);
            intent.putExtra(UPDATE_PROGRESS, updateProgress);
            intent.putExtra(DOWNLOAD_NOTIFICATION_FLAG, downloadNotificationFlag);
            intent.putExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, downloadSuccessNotificationFlag);
            intent.putExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, downloadErrorNotificationFlag);
            intent.putExtra(IS_SEND_BROADCAST, isSendBroadcast);
            intent.putExtra(DOWNLOAD_NOTIFICATION_TITLE, title);
            context.startService(intent);

            return this;
        }

        private int getIcon(Context context) {

            final PackageManager packageManager = context.getPackageManager();
            ApplicationInfo appInfo = null;
            try {
                appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (appInfo != null) {
                return appInfo.icon;
            }
            return 0;
        }

        public ServiceConnection getConnection() {
            return connection;
        }

        public Builder setConnection(ServiceConnection connection) {
            this.connection = connection;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }
    }
}
